package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.BaseInfoDto;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.Article;
import com.itheima.ydd.entity.Config;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private CateService cateService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private AdvposService advposService;

    @Autowired
    private TagService tagService;

    @Autowired
    private AdvimgService advimgService;

    @Autowired
    private YddUserService yddUserService;


    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultData login(@RequestBody User user) {

        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLoginName, user.getLoginName());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        if (loginUser.getStatus() == 0) {
            throw new BusinessException("该用户已被禁用!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功

        // 生成token信息
        String roleId = loginUser.getRoleId()
                .replace("[", "")
                .replace("]", "")
                .replace("\"", "");

        tokenMap.put("id", loginUser.getId());
        tokenMap.put("roleId", roleId);

        String token = JwtUtils.getToken(tokenMap);
        retMap.put("token", token);

        return ResultData.ok("", retMap);
    }


    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {

        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttrKey(), config.getAttrValue());
        }
        return ResultData.ok("", map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {

        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }


    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }

    @GetMapping("/baseInfo")
    public ResultData baseInfo() {

        BaseInfoDto baseInfoDto = new BaseInfoDto();
        baseInfoDto.setArticleNum(0);

        // 所有分类数据
        List<CateDto> cateDtoList = cateService.list().stream().map(cate -> {
            CateDto cateDto = new CateDto();
            BeanUtils.copyProperties(cate, cateDto);
            LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Article::getCateId, cate.getId());
            int count = articleService.count(queryWrapper);
            cateDto.setNum(count);
            // 文章总数
            baseInfoDto.setArticleNum(baseInfoDto.getArticleNum() + count);
            return cateDto;
        }).collect(Collectors.toList());
        baseInfoDto.setAllCateList(cateDtoList);

        // 广告位总数
        baseInfoDto.setAdvposNum(advposService.count());

        // 标签总数
        baseInfoDto.setTagNum(tagService.count());

        // 管理员总数
        baseInfoDto.setAdminNum(userService.count());

        // 广告分类总数
        baseInfoDto.setCateNum(cateDtoList.size());

        // 广告图总数
        baseInfoDto.setAdvimgNum(advimgService.count());

        {
            // 最新用户数据
            LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(YddUser::getId, YddUser::getUsername, YddUser::getSex, YddUser::getAddress, YddUser::getIcon);
            // 默认数据
            // queryWrapper.eq(YddUser::getDefaultData, 1);
            queryWrapper.orderByDesc(YddUser::getId);
            queryWrapper.last("limit 7");
            baseInfoDto.setNewUserList(yddUserService.list(queryWrapper));
        }

        {
            // 热门文章数据
            LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Article::getId, Article::getTitle, Article::getAuthor, Article::getKeywords, Article::getClick);
            queryWrapper.orderByDesc(Article::getClick);
            queryWrapper.last("limit 7");
            baseInfoDto.setHotArticleList(articleService.list(queryWrapper));
        }

        {
            // 用户数据
            UserDto userDto = new UserDto();
            LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddUser::getSex, 0);
            int womanNum = yddUserService.count(queryWrapper);
            int allNum = yddUserService.count();
            userDto.setTotal(allNum);
            userDto.setUserWoman(womanNum);
            userDto.setUserMan(allNum - womanNum);
            baseInfoDto.setUser(userDto);
        }

        return ResultData.ok("", baseInfoDto);
    }
}
